package apigateway.serviceRegister;

import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 小泽玛丽罗 on 2017/3/5.
 */
@Component
public class CombinationServiceRegister {

    @Value("${service.type}")
    private String serviceType;
    @Value("${service.name}")
    private String name;
    @Value("${service.ip}")
    private String ip;
    @Value("${service.port}")
    private int port;
    @Value("#{'${service.dependency.locations}'.split(',')}")
    private List<String> dependencyLocations;
    @Value("${service.dependency.serviceName}")
    private String dependencyServiceName;
    @Value("${service.dependency.serviceCategory}")
    private String dependencyServiceCategory;
    @Value("${service.registePath}")
    private String registerPath;
    @Value("${service.parentPath}")
    private String registerParentPath;
    @Value("${zookeeper.ip}")
    private String zkPath;
    private ServiceNode serviceNode;
    @Value("${service.weight}")
    private int weight;
    @PostConstruct
    private void RegisterCombinationService(){
        List<Dependecy> dependecies=new ArrayList<>();
        for(String dependLocation:dependencyLocations){
            dependecies.add(new Dependecy(dependLocation
                    ,dependencyServiceCategory,dependencyServiceName));
        }
         serviceNode=new ServiceNode(ip,port,"combination"
                ,registerPath,"",dependencyServiceName
                ,dependencyServiceCategory,weight);
        serviceNode.getDependencies().addAll(dependecies);
        ZkClient zkClient=new ZkClient(zkPath,5000);
        if(zkClient.exists(registerPath)){
            zkClient.writeData(registerPath,serviceNode);
        }else {
            zkClient.createPersistent(registerParentPath,true);
            zkClient.createEphemeral(registerPath,serviceNode);
        }
    }

    public ServiceNode getServiceNode() {
        return serviceNode;
    }
}
